# -- coding: utf-8 --
import subprocess, shutil, os,stat,random
import sys, traceback, time, re
from httplib import HTTPConnection
import urllib, urllib2
from json import JSONDecoder
import json
import codecs
import get_pbi

debug_flag = 1

class sync_commit_to_alm():
    def _sync_data_to_alm(self,commit_info,git_url,pbi):
        log_lines = commit_info.split('\n')
        commit_hash = ''
        commit_name = ''
        commit_date = ''
        dts_or_num = ''
        dts_info = ''
        reason_info = ''
        file_lst = []
        line = 0
        owner = commit_info.split('owner:')[1].split('url:')[0]
        for log_line in log_lines:
            if 13 == line:
                temp_info = log_line.split('commit_detail:')[1].replace('\n','')
                list = re.findall('^\s*DTS.*|S184088',temp_info)
                if len(list) >= 1:
                    print "DTS , no need to sync, skip"
                    return True
            if 14 == line:
                dts_info = log_line.split('reason:')[1].split('\n')[0].strip()
                if ';' in dts_info:
                    dts_info = dts_info.split(';')[0].strip()
            elif 15 == line:
                reason = log_line.replace('\n','')
            line += 1
            if 'Change-Id:' in log_line:
                change_id = log_line.split('Change-Id:')[1].split('\n')[0].strip()
            elif 'lastUpdated:' in log_line:
                commit_date = log_line.split('lastUpdated:')[1].strip()
        files = commit_info.split('files:')[1:]
        commit_name = owner.split('name:')[1].split('\n')[0].split(' ')[2].strip() 
        for i in range(len(files)):
            if 'file:' not in files[i]:
                continue
            operation = files[i].split('type:')[1].split('\n')[0].strip()
            file_path = files[i].split('file:')[1].split('\n')[0].strip()
            file_lst.append({"operation":operation, "file_path":file_path, "file_version":""})
        
        if debug_flag == 1:
            print "-------------------------------------------------------------"
            print "Debug info:"
            print "change_id:" + change_id, "author:" + commit_name, "date:" + commit_date
            print "file_list = " + str(file_lst)
            print "-------------------------------------------------------------"
        dts_or_num = dts_info
        if dts_or_num == '':
            print 'dts_or_num is null.'
            return False
        #if SCF, the real number should at reason section
        if '.' in dts_or_num:
            ticket_header=dts_or_num.split('.')[0]
        else:
            ticket_header=dts_or_num.split('_')[0]
        type = 'AR Node'
        if 'dts' in dts_or_num.lower():
            type = 'Defect'
        if 'SR' == ticket_header:
            type = 'SR Node'
        elif 'AR' == ticket_header:
            type = 'AR Node'
        print '提交信息到alm系统'
        url = '/alm/services/codeConfig/codeCp/save/'
        bodys = {"params":{"scm_type":"Git","item_id":[""],"number":[dts_or_num],"type":[type],"description":dts_or_num,"version":change_id,"server_url":git_url,"createBy":commit_name,"pbi_id":pbi,"file_list":file_lst}}
        bodys = json.dumps(bodys, ensure_ascii=False, encoding='UTF-8')
        headers = {"Content-type": "application/json","Accept": "application/json","Charset":"UTF-8","username":"EulerOS_gerrit_mks_user","password":"EulerOS_gerrit_mks_pwd","operator":"rwx403335"}
        ret,out = self._execute_rest_api(url, 'POST', bodys, host = 'alm.huawei.com', headers = headers, urlencode = False)
        print 'http response from alm: out = ' + str(out)
        return ret

    def _execute_rest_api(self, url, method, param, host='10.175.124.204:8080', headers = None, urlencode = False):
        reload(sys)
        sys.setdefaultencoding('utf-8')
        #data = urllib.urlencode(param)
        if (method.upper() == "GET") and (data != ""):
            url = url + "?"+data
        if headers is None:
            headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain","Charset":"UTF-8"}
        http_conn = HTTPConnection(host,timeout=600000)
        try:
            if urlencode:
                post_data = urllib.urlencode(param)
            else:
                post_data = str(param)
            if debug_flag == 1:
                print "-------------------------------------------------------------"
                print "Debug info:"
                print "url = " + url 
                print "post_data = " + str(post_data)
                print "headers = " + str(headers)
                print "-------------------------------------------------------------"
                #http_conn.set_debuglevel(1)
            http_conn.request(method, url, post_data, headers=headers)

            response = http_conn.getresponse()
            response_status = response.status
            response_content = response.read()
            if debug_flag == 1:
                print "-------------------------------------------------------------"
                print "Debug info:"
                print response_status,response_content
                print "-------------------------------------------------------------"
            http_conn.close()

            if (response_status  >=300):
                return False,response_content
            else:
                try:
                    rst = JSONDecoder().decode(response_content)
                except ValueError:
                    rst = response_content
                return True,rst
        except:
            print "".join(traceback.format_exception(*sys.exc_info()))
            return False,{}

    def execute(self,msg):
        git_url = msg.split('url:')[1].split('\n')[0].replace(' ', '').replace('=','')
        branch = msg.split('branch')[1].split('\n')[0]
        if debug_flag == 1:
            print "-------------------------------------------------------------"
            print "Debug info:"
            print "git_url = " + git_url
            print "msg = " + msg
            print "branch = " + branch
            print "-------------------------------------------------------------"
        pbi_obj = open("product_pbi.ini")
        pbi_info = pbi_obj.read()
        pbi_obj.close()
        pbi_euler = pbi_info.split('EulerOS_Server_V200R008C00')[1].split('\n')[0].strip()
        pbi_uvparm = pbi_info.split('UVP_ARM_3.0.0')[1].split('\n')[0].strip()
        pbi_uvpkvm = pbi_info.split('UVP_KVM_3.0.0')[1].split('\n')[0].strip()
        pbi_list = [pbi_euler,pbi_uvparm,pbi_uvpkvm]
        try:
            print 'the time is ' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + ',start to merge.'
            for pbi in pbi_list:
                print "pbi:[" + pbi + "]"
                ret = self._sync_data_to_alm(msg,git_url,pbi)
            if ret == False:
                return 1
            print 'the time is ' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + ',end merge.'
        except:
            print "".join(traceback.format_exception(*sys.exc_info()))
            return 1
        return 0

if __name__ == '__main__':
    #pass
    if len(sys.argv) < 2:
        print "Need more paramaters."
        sys.exit(1)
    ID = sys.argv[1]
    result =  os.popen("ssh -p 29418 peulerosci@dgggit09-rd.huawei.com gerrit query --files --patch-sets change:" + ID)
    msg = result.read()
    merge_obj = sync_commit_to_alm()
    ret = merge_obj.execute(msg)
    sys.exit(ret)
